//
// Created by LiuYou on 2021/8/12.
//



#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cassert>
#include <unistd.h>


/**
 * CGI服务器原理
 */
int main(int argc, char** argv) {
    if (argc < 3) {
        fprintf( stderr, "用法: %s ip port\n", basename( argv[0] ));
        exit( 1 );
    }

    char* ip = argv[1];
    int port = atoi( argv[2] );

    sockaddr_in localAddress;
    localAddress.sin_family = AF_INET;
    inet_pton( AF_INET, ip, &localAddress.sin_addr );
    localAddress.sin_port = htons( port );

    int socketFd = socket( AF_INET, SOCK_STREAM, 0 );
    assert( socketFd >= 0 );

    int ret = bind( socketFd, (sockaddr*) &localAddress, sizeof( localAddress ));
    assert( ret != -1 );

    ret = listen( socketFd, 5 );
    assert( ret != -1 );

    sockaddr_in remoteAddress;
    socklen_t socklen = sizeof( remoteAddress );
    int connectFd = accept( socketFd, (sockaddr*) &remoteAddress, &socklen );
    if (connectFd < 0) {
        perror( "accept()" );
        close( socketFd );
        exit( 1 );
    }

    close( STDOUT_FILENO );
    dup( connectFd );
    printf( "abcd\n" );
    close( connectFd );



    close( socketFd );
    return 0;
}